package com.woniuxy.microsystemsarserver.controller;

import com.github.pagehelper.PageInfo;
import com.slsupermarket.common.res.ResponseMsg;
import com.woniuxy.microsystemsarserver.bean.InvoiceBean;
import com.woniuxy.microsystemsarserver.bean.PageRequestBean;
import com.woniuxy.microsystemsarserver.bean.StoreBean;
import com.woniuxy.microsystemsarserver.service.IInvoiceService;
import com.woniuxy.microsystemsarserver.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 发票记录
 * @author 杨灿
 */
@RestController
@RequestMapping("/invoice")
public class InvoiceController {
    @Resource
    private IInvoiceService invoiceService;
    /**
     * 分页查询发票记录信息
     * @param invoiceBean
     * @param currentPage
     * @param userId
     * @return
     */
    @RequestMapping("/allByPage")
    public ResponseMsg findByPage(InvoiceBean invoiceBean, Integer currentPage, Long userId){
        PageRequestBean pageRequestBean = new PageRequestBean();
        pageRequestBean.setPageNum(currentPage);
        pageRequestBean.setLimit(5);
        PageInfo<InvoiceBean> byPage = invoiceService.findByPage(invoiceBean, pageRequestBean, userId);
        return new ResponseMsg().builder().code(200).data(byPage).msg("查询成功").build();
    }
    /**
     * 添加发票记录信息
     * @param invoiceBean
     * @param userId
     * @return
     */
    @RequestMapping("/add")
    public ResponseMsg saveInvoice(InvoiceBean invoiceBean,Long userId){
        invoiceBean.setFkUserId(userId);
        int row = invoiceService.saveInvoice(invoiceBean);
        if (row>0){
            return new ResponseMsg().builder().code(200).msg("添加成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("添加失败").build();
        }

    }

    /**
     * 修改发票信息
     * @param invoiceBean
     * @return
     */
    @RequestMapping("/update")
    public ResponseMsg updateInvoice(InvoiceBean invoiceBean){

        int row = invoiceService.updateInvoice(invoiceBean);
        if (row>0){
            return new ResponseMsg().builder().code(200).msg("修改成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("修改失败").build();
        }

    }
    /**
     * 根据id查询发票信息
     * @param invoiceId
     * @return
     */
    @RequestMapping("/findById")
    public ResponseMsg findById(Long invoiceId){

        InvoiceBean byId = invoiceService.findById(invoiceId);

        if (byId!=null){
            return new ResponseMsg().builder().code(200).data(byId).msg("查询成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("查询失败").build();
        }
    }

    /**
     * 查询指定用户所有发票信息
     * @param userId
     * @return
     */
    @RequestMapping("/all")
    public ResponseMsg findAll(Long userId){

        List<InvoiceBean> all = invoiceService.findAll(userId);

        if (all!=null){
            return new ResponseMsg().builder().code(200).data(all).msg("查询成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("查询失败").build();
        }
    }

    /**
     *导出当前用户的发票记录信息为excel
     * @return
     */
    @RequestMapping("/exportAll")
    public ResponseMsg exportAudit(long userId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取数据
        List<InvoiceBean> list = invoiceService.findAll(userId);
        // System.out.println(list);
        //excel标题
        String[] title = {"序号","开票金额","发票类型","发票内容","发票抬头","备注","状态"};

        //excel文件名
        String fileName = "发票记录表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "发票记录表";
        String[][] content = new String[list.size()+1][title.length];
        for (int i = 0; i < list.size(); i++) {
            InvoiceBean obj = list.get(i);
            content[i][0] = i+1 +"";
            content[i][1] = obj.getServiceOrderBean().getRealMoney()+"";
            if (obj.getInvoiceStyle()==0){
                content[i][2] = "电子发票";
            }else if (obj.getInvoiceStyle()==1){
                content[i][2] = "增值税发票";
            }else if(obj.getInvoiceStyle()==2){
                content[i][2] = "增值税专用发票";
            }

            content[i][3] = obj.getInvoiceContent();
            content[i][4] = obj.getInvoiceHead();
            content[i][5] = obj.getRemark();
            if (obj.getInvoiceStatus()==0){
                content[i][6] = "开票中";
            }else if (obj.getInvoiceStatus()==1){
                content[i][6] = "已开票";
            }else if(obj.getInvoiceStatus()==2){
                content[i][6] = "开票失败";
            }

        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response,fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送响应流方法
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/x-msdownload;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
